<template>
    <div class="userInfoContainer">
        <el-form ref="form" :model="goodForm" label-width="80px">
            <el-form-item label="商品封面">
                <img class="avatar" :src="goodForm.cover">
                <br>更改头像
                <input type="file" @input="upFile($event)">
            </el-form-item>

            <el-form-item label="商品名">
                <el-input v-model="goodForm.name"></el-input>
            </el-form-item>

            <el-form-item label="商品价格">
                <el-input-number v-model="goodForm.price" :precision="2" :step="0.1" :max="999999999"></el-input-number>
            </el-form-item>

            <el-form-item label="商品简介">
                <el-input v-model="goodForm.description"></el-input>
            </el-form-item>

            <el-form-item label="商品类型">
                <el-cascader
                v-model="goodForm.type"
                :options="typeOptions"
                :props="{ checkStrictly: true, emitPath:false }"
                clearable></el-cascader>
            </el-form-item>

            <el-form-item label="所属店铺">
                <el-select v-model="shopId" filterable placeholder="请选择">
                    <el-option
                        v-for="item in shopOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                    </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="addAndUpdate">{{operation}}</el-button>
                <el-button @click="reset">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
import fileStore  from '@/api/fileStore';
import good from '@/api/good';
import goodType from '@/api/goodType';
import shop from '@/api/shop';
import shopService from '@/api/shopService';
export default {
    data(){
        return {
            id:null,
            goodForm:{
                id:null,
                name:'',
                price:'',
                type:'',
                description:'',
                cover:'',
            },
            shopId:null,
            typeOptions:[
                {
                    value:'',
                    lable:'',
                    children:[]
                },
            ],
            shopOptions:[
                {
                    value:'',
                    lable:'',
                    children:[]
                },
            ],
        }
    },
    created() {
      //初始化 
      this.init()
    },
    watch:{ //当页面路由发生变化时就会执行
      $route(to,from) {
          this.init();
      }
    },
    methods: {
      //初始化操作
      init() {
          this.searchTypes();
          this.getAllShops();
          //当前页面是否携带id,带id查询出值
          if(this.$route.params && this.$route.params.id && this.$route.params.id.length > 1) {
              var temp = this.$route.params.id;
              this.id  = temp;
              this.goodForm.id = this.id;
              this.operation="修改"
              this.getGood();
          } else { //路径没有id值
              //清空表单
              this.operation="创建"
              this.reset()
          }
      },    
      getAllShops(){
        shop.getAll()
            .then(response=>{
                this.shopOptions = JSON.parse(JSON.stringify(response.data.list).replace(/id/g,"value"));
            })
      },
      //查询所有分类
      searchTypes(){
        goodType.getData()
            .then(response=>{
                var treeData = response.data.list;
                this.typeOptions = JSON.parse(JSON.stringify(treeData).replace(/id/g,"value"));
            })
      },
      //获取商品
      getGood(){
        good.get(this.id)
            .then(response=>{
                this.goodForm = response.data.good;
            })
      },
      //修改和添加商品
      addAndUpdate(){
        if(!this.checkForm()){
            return;
        }
        if(this.goodForm.id){
            //修改
            good.update(this.goodForm)
                .then(response=>{
                        this.$message({
                            message: '修改成功',
                            type: 'success'
                        });
                    this.reset();
                    this.$router.push({path:'/goods/list'})
                })
        }else{
            if(this.shopId == null){
                this.$message({
                    message: '店铺不能为空',
                    type: 'error'
                });
                return;
            }
            //增加商品
            good.add(this.goodForm)
                .then(response=>{
                    //商品添加到店铺
                    shopService.add({shopId:this.shopId,goodId:response.data.good.id})
                        .then(response=>{
                            this.$message({
                                message: '添加成功',
                                type: 'success'
                            });
                            this.reset();
                            this.$router.push({path:'/goods/list'})
                        })
                })
        }
      },
      //上传文件检查
      checkFile(file) {
        var reg = new RegExp(".*\\.(jpg|jpeg|png|gif|bmp|svg)$");
        const isJPG = reg.test(file.name);
        const isLt2M = file.size / 1024 / 1024 < 10;
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG/png/gif 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 10MB!');
        }
        return isJPG && isLt2M;
      },
      //检查数据
      checkForm(){
        if(this.goodForm.name.length >= 1 && this.goodForm.description.length >=1){
            return true;
        }
        this.goodForm.price = parseFloat(this.goodForm.price);
        this.$message('简介和名称不能为空');
        return false;
      },
      //加载文件
      loadFile(file){
        return new Promise((success)=>{
            //读取文件流
            var reader = new FileReader();
            var binData=null;
            let data = reader.readAsArrayBuffer(file);
            reader.addEventListener('load',(e=>{
                binData = new Blob([e.target.result],{type:file.type});
                success(binData);
            }));
        })
      },
      //上传文件
      async upFile(event){
        var file = event.target.files[0];
        if(!this.checkFile(file)){
            return;
        }
        var binData = await this.loadFile(file);
        //封装文件
        var upload = new FormData();
        //参数名 文件 文件名
        upload.append('file',binData,file.name);
        fileStore.upLoadFile(upload)
            .then(response=>{
                console.log(typeof this.goodForm.cover);
                //上传文件后检查头像是否已经存在
                if(this.goodForm.cover == response.data.file.url){
                    this.$message.success('更换成功');
                    return;
                }
                if(this.goodForm.cover.length > 1){
                    console.log(this.goodForm.cover);
                    fileStore.deleteFile(this.goodForm.cover)
                        .then(response=>{
                            this.$message.success('更换成功');
                        })
                }
                this.goodForm.cover = response.data.file.url;
            })
      },
      //重置条件
      reset(){
        this.goodForm.name='';
        this.goodForm.cover='';
        this.goodForm.price='';
        this.goodForm.description='';
        this.goodForm.type='';
        this.searchTypes();
        this.goodForm.id = this.id;
        this.id = null;
      }
    }
}
</script>
<style>
.userInfoContainer {
    margin-top: 10%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
.search{
    position: relative;
    bottom: 10px;
    left: 40%;
    margin-top: -20px;
    width: 200px;
    /* display: none; */
}
.searchText{
    display: block;
    width: 150px;
    height: 20px;
    border: none;
    border-bottom: 1px solid rgb(130, 195, 233);
    outline: none;
}

.searchText:hover{
    background-color: rgb(103, 173, 235);
    color: white;
}
</style>